<script setup>
import { ref, nextTick } from 'vue'
import { Plus, Edit, Delete, ZoomOut, Close } from '@element-plus/icons-vue'
import { reqGetCategory1, reqGetCategory2, reqGetCategory3, reqGetAttrList } from '@/api/brand'
import { reqGetSpuList, reqGetBaseTrademarkList, reqGetSpuImageList, reqGetSpuSaleAttrList, reqGetAllSaleAttrList, reqUpdateSpu, reqAddSpu, reqDeleteSpu, reqAddSku,reqGetSkuList } from '@/api/spu'
const formInline = ref({
  oneregion: '',
  towregion: '',
  threeregion: '',
})
// 一级分类数据
const category1s = ref([])
const category2s = ref([])
const category3s = ref([])
const spuList = ref([])
// 获取一级分类数据
const getCategory1 = async () => {
  const res = await reqGetCategory1()
  if (res.code === 200) {
    category1s.value = res.data
  }
}
getCategory1()
const towDisabled = ref(true)
const threeDisabled = ref(true)
// 监听一级分类
const handerChangeOne = async () => {
  const res = await reqGetCategory2(formInline.value.oneregion)
  if (res.code === 200) {
    category2s.value = res.data
    towDisabled.value = false
  }
}
// 监听二级分类
const handerChangeTow = async () => {
  const res = await reqGetCategory3(formInline.value.towregion)
  if (res.code === 200) {
    category3s.value = res.data
    threeDisabled.value = false
  }
}
// 监听三级分类
const handerChangeThree = async () => {
  const res = await reqGetSpuList(page.value, limit.value, formInline.value.threeregion)
  if (res.code === 200) {
    spuList.value = res.data.records
    total.value = res.data.total
  }
}

// 分页器数据
const page = ref(1)
const limit = ref(3)
const total = ref()
// 修改
const handleEdit = () => {

}
// 删除
const handleDelete = async (row) => {
  const res = await reqDeleteSpu(row.id)
  if (res.code === 200) {
    handerChangeThree()
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
  }
}
// 每页个数改变
const handleSizeChange = (val) => {
  limit.value = val
  handerChangeThree()
}
// 改变页码
const handleCurrentChange = (val) => {
  page.value = val
  handerChangeThree()
}
const status = ref(0)
const saveType = ref()

// 新增spu
const handleAdd = async () => {
  saveType.value = 'add'
  status.value = 1
  getBaseTrademarkList()
  spuForm.value = {
    spuName: '',
    tmId: '',
    description: '',
    spuImageList: [],
    spuSaleAttrList: [],
    id: ''
  }
  getAllSaleAttrList()

}

// 获取所有的品牌数据
const getBaseTrademarkList = async () => {
  const res = await reqGetBaseTrademarkList()
  if (res.code === 200) {
    trademarkList.value = res.data
  }
}

const saleAttrList = ref([])
// 获取所有的销售属性
const getAllSaleAttrList = async () => {
  let idsInArray2 = new Set(spuForm.value.spuSaleAttrList.map(obj => obj.saleAttrName));
  console.log("idsInArray2", idsInArray2);
  const res = await reqGetAllSaleAttrList()
  if (res.code === 200) {
    saleAttrList.value = res.data.filter(obj1 => !idsInArray2.has(obj1.name))
    console.log("saleAttrList.value", saleAttrList.value);
  }
}


// 编辑spu
const handleEditSpu = async (row) => {
  saveType.value = 'edit'
  status.value = 1
  spuForm.value.spuName = row.spuName
  spuForm.value.description = row.description
  spuForm.value.tmId = row.tmId
  spuForm.value.id = row.id
  getBaseTrademarkList()
  const res = await reqGetSpuImageList(row.id)
  if (res.code === 200) {
    spuForm.value.spuImageList = res.data.map(item => {
      return {
        url: item.imgUrl,
        name: item.imgName,
      }
    })
  }
  const res2 = await reqGetSpuSaleAttrList(row.id)
  if (res2.code === 200) {
    spuForm.value.spuSaleAttrList = res2.data
  }
  getAllSaleAttrList()
}

const dialogTableVisible = ref(false)
const gridData = ref([])
// 查看sku
const handleCheckSpu = async (row) => {
  dialogTableVisible.value = true
  const res = await reqGetSkuList(row.id)
  if (res.code === 200) {
    gridData.value = res.data
  }
}

// 收集spu数据
const spuForm = ref({
  spuName: '',
  tmId: '',
  description: '',
  spuImageList: [],
  spuSaleAttrList: [],
  id: ''
})
// 所有的SPU品牌数据
const trademarkList = ref([])
// 文件上传成功前
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片必须是jpg格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片不能超过2MB!')
    return false
  }
  return true
}
// 文件上传成功后
const handleAvatarSuccess = (response, uploadFile) => {

}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
// 销售属性的值

const InputRef = ref()
const saleAttrIdAndValueName = ref('')

// 选择销售属性
const handleChangeSaleAttr = () => {
  console.log(saleAttrIdAndValueName.value);
}

// 已选择的标签
const handleClose = (index, tagIddex) => {
  spuForm.value.spuSaleAttrList[index].spuSaleAttrValueList.splice(tagIddex, 1)
}
const showInput = (index, row) => {
  row.selected = true
  row.attrValue = ''
  nextTick(() => {
    InputRef.value.input.focus()
  })
}

const handleInputConfirm = (index, row) => {
  if (row.attrValue) {
    spuForm.value.spuSaleAttrList[index].spuSaleAttrValueList.push({
      saleAttrValueName: row.attrValue,
      baseSaleAttrId: row.baseSaleAttrId,
    })
  }
  spuForm.value.spuSaleAttrList.forEach(item => {
    item.selected = false
  })
}
// 添加销售属性
const handleAddSaleAttr = () => {
  let [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  spuForm.value.spuSaleAttrList.push({
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  })
  saleAttrIdAndValueName.value = ''
  saleAttrList.value = saleAttrList.value.filter(item => item.id != baseSaleAttrId)

}
// 删除销售属性
const handleDeleteSaleAttr = (index, row) => {
  spuForm.value.spuSaleAttrList.splice(index, 1)
  saleAttrList.value.push({
    id: row.baseSaleAttrId,
    name: row.saleAttrName
  })
}


// 保存
const handleSaveSpu = async () => {
  let spu = {
    category3Id: formInline.value.threeregion,
    description: spuForm.value.description,
    spuName: spuForm.value.spuName,
    tmId: spuForm.value.tmId,
    spuImageList: spuForm.value.spuImageList.map(item => {
      return {
        imgName: item.name,
        imgUrl: item.response?.data || item.url,
      }
    }),
    spuSaleAttrList: spuForm.value.spuSaleAttrList
  }
  if (saveType.value === 'add') {
    page.value = 1
    const res = await reqAddSpu(spu)
    if (res.code === 200) {
      ElMessage.success('添加成功')
      status.value = 0
    }
  } else {
    spu.id = spuForm.value.id
    const res = await reqUpdateSpu(spu)
    if (res.code === 200) {
      ElMessage.success('修改成功')
      status.value = 0
    }
  }
  handerChangeThree()
}


// 添加sku的所有信息
const skuForm = ref({
  spuId:'',
  tmId:'',
  skuName: '',
  skuPrice: '',
  skuWeight: '',
  description: '',
  ptAttributeList: [],
  spuSaleAttrList: [],
  spuImageList: [],
  skuDefaultImg:''
})

// 新增sku
const handleAddSku = async (row) => {
  skuForm.value.skuName = ''
  skuForm.value.skuPrice = ''
  skuForm.value.skuWeight = ''
  skuForm.value.description = ''
  skuForm.value.skuDefaultImg = ''
  skuForm.value.spuId = row.id
  skuForm.value.tmId = row.tmId
  status.value = 2
  // 同时发出三个请求
  const [res, res2, res3] = await Promise.all([
    reqGetSpuImageList(row.id),
    reqGetSpuSaleAttrList(row.id),
    reqGetAttrList(formInline.value.oneregion, formInline.value.towregion, formInline.value.threeregion),
  ]);

  // 处理请求结果
  if (res.code === 200) { 
    skuForm.value.spuImageList = res.data;
  }
  if (res2.code === 200) {
    skuForm.value.spuSaleAttrList = res2.data;
  }
  if (res3.code === 200) {
    skuForm.value.ptAttributeList = res3.data;
  }
}
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 销售属性改变
const handleChangeSaleAttrValue = (item) => {
}

// 设置为默认
const handleDefault = (index, row) => {
  skuForm.value.spuImageList.forEach(item => {
    item.isDefault = false
  })
  row.isDefault = true
  skuForm.value.skuDefaultImg = row.imgUrl
}

// 保存
const handleSaveSku = async () => {

  let skuAttrValueList = skuForm.value.ptAttributeList.map(item => {
    return {
      attrId: item.id,
      valueId: item.salePtSelectSkuValue,
    }
  })

  let skuSaleAttrValueList = skuForm.value.spuSaleAttrList.map(item => {
    return {
      saleAttrId: item.id,
      saleAttrValueId: item.saleSelectSkuValue,
    }
  })
  
  const res = await reqAddSku({
    category3Id: formInline.value.threeregion,
    spuId: skuForm.value.spuId,
    tmId: skuForm.value.tmId,
    skuName: skuForm.value.skuName,
    price: skuForm.value.skuPrice,
    skuDesc: skuForm.value.description,
    weight: skuForm.value.skuWeight,
    skuAttrValueList,
    skuSaleAttrValueList,
    skuDefaultImg: skuForm.value.skuDefaultImg,
  })
  if (res.code === 200) {
    ElMessage.success('添加成功')
    status.value = 0
  }

}
</script>

<template>
  <el-card>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="一级分类">
        <el-select v-model="formInline.oneregion" placeholder="请选择一级分类" @change="handerChangeOne">
          <el-option v-for="item in category1s" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select v-model="formInline.towregion" placeholder="请选择二级分类" :disabled="towDisabled"
          @change="handerChangeTow">
          <el-option v-for="item in category2s" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select v-model="formInline.threeregion" placeholder="请选择三级分类" :disabled="threeDisabled"
          @change="handerChangeThree">
          <el-option v-for="item in category3s" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin-top: 20px;">
    <div v-if="status === 0">
      <div class="btn"> <el-button type="primary" :icon="Plus" @click="handleAdd"
          :disabled="!formInline.threeregion">添加SPU</el-button></div>
      <el-table :data="spuList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="100" align="center">
        </el-table-column>
        <el-table-column prop="spuName" label="SPU名称" width="auto"> </el-table-column>
        <el-table-column prop="description" label="SPU描述" width="auto"> </el-table-column>
        <el-table-column label="SPU操作">
          <template #default="{ row }">
            <el-button size="large" type="warning" :icon="Plus" circle @click="handleAddSku(row)" />
            <el-button size="large" type="primary" :icon="Edit" circle @click="handleEditSpu(row)" />
            <el-button size="large" type="info" :icon="ZoomOut" circle @click="handleCheckSpu(row)" />

            <el-popconfirm title="确认删除吗？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button size="large" type="danger" :icon="Delete" circle />
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[3, 6, 9, 12]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <div v-else-if="status === 1">
      <el-form :model="spuForm" label-width="auto">
        <el-form-item label="SPU名称">
          <el-input v-model="spuForm.spuName" placeholder="请输入SPU名称" />
        </el-form-item>
        <el-form-item label="SPU品牌">
          <el-select v-model="spuForm.tmId" placeholder="请选择SPU品牌" style="width:400px">
            <el-option v-for="item in trademarkList" :key="item.id" :label="item.tmName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
          <el-input v-model="spuForm.description" placeholder="请输入SPU描述" />
        </el-form-item>
        <el-form-item label="SPU照片">
          <el-upload v-model:file-list="spuForm.spuImageList" action="/api/admin/product/fileUpload"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="SPU销售属性" label-width="auto">
          <div style="display: flex;gap: 0 20px; margin-bottom: 20px;">
            <el-select v-model="saleAttrIdAndValueName"
              :placeholder="saleAttrList.length > 0 ? '还有' + saleAttrList.length + '个属性可选' : '暂无选择'" style="width:400px"
              :disabled="saleAttrList.length == 0" @change="handleChangeSaleAttr">
              <el-option :label="item.name" :value="`${item.id}:${item.name}`" v-for="item in saleAttrList"
                :key="item.id" />
            </el-select>
            <el-button type="primary" :icon="Plus" @click="handleAddSaleAttr"
              :disabled="!saleAttrIdAndValueName">添加销售属性</el-button>
          </div>
          <el-table :data="spuForm.spuSaleAttrList" border style="width: 100%">
            <el-table-column type="index" label="序号" width="100" align="center"> </el-table-column>
            <el-table-column prop="saleAttrName" label="属性名" width="auto">
            </el-table-column>
            <el-table-column label="属性值" width="auto">
              <template #default="{ $index, row }">
                <!-- <el-input v-model="row.saleAttrValueName" placeholder="请输入属性值" /> -->
                <!-- <el-button type="primary" :icon="Plus" circle @click="handleAddSaleAttrValue(row)" /> -->
                <span style="display: flex;gap: 0 20px;">
                  <el-tag v-for="(tag, tagIndex) in row.spuSaleAttrValueList" :key="tag.id" closable
                    :disable-transitions="false" @close="handleClose($index, tagIndex)">
                    {{ tag.saleAttrValueName }}
                  </el-tag>
                  <el-input v-if="row.selected" ref="InputRef" v-model="row.attrValue" class="w-20" size="small"
                    @keyup.enter="handleInputConfirm($index, row)" @blur="handleInputConfirm($index, row)"
                    style="width: 100px;" />
                  <el-button v-else type="primary" class="button-new-tag" size="small" :icon="Plus"
                    @click="showInput($index, row)">
                    <!-- <el-button type="primary" :icon="Plus" @click="handleAddSaleAttrValue(row)" /> -->
                  </el-button>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ $index, row }">
                <el-button type="danger" :icon="Delete" circle @click="handleDeleteSaleAttr($index, row)" />
              </template>
            </el-table-column></el-table>
        </el-form-item>
        <el-form-item style="margin-left: 100px;">
          <el-button type="primary" @click="handleSaveSpu">保存</el-button>
          <el-button @click="status = 0">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-else-if="status === 2">
      <el-form :model="skuForm" label-width="auto">
        <el-form-item label="SKU名称">
          <el-input v-model="skuForm.skuName" placeholder="SKU名称" />
        </el-form-item>
        <el-form-item label="价格(元)">
          <el-input v-model="skuForm.skuPrice" placeholder="价格(元)" />
        </el-form-item>
        <el-form-item label="重量(克)">
          <el-input v-model="skuForm.skuWeight" placeholder="重量(克)" />
        </el-form-item>
        <el-form-item label="SKU描述">
          <el-input v-model="skuForm.description" placeholder="SKU描述" />
        </el-form-item>
        <el-form-item label="平台属性">
          <el-form :inline="true" :model="skuForm.ptAttributeList">
            <el-form-item v-for="item in skuForm.ptAttributeList" :key="item.id" :label="item.attrName"
              style="width: 400px; margin-bottom: 20px;">
              <el-select v-model="item.salePtSelectSkuValue" placeholder="请选择">
                <el-option v-for="(it, index) in item.attrValueList" :key="it.id" :label="it.valueName"
                  :value="it.id" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-form-item>
        <el-form-item label="销售属性">
          <el-form :inline="true" :model="skuForm.spuSaleAttrList">
            <el-form-item :label="item.saleAttrName" v-for="item in skuForm.spuSaleAttrList" :key="item.id"
              style="width: 400px;">
              <el-select v-model="item.saleSelectSkuValue" placeholder="请选择" @change="handleChangeSaleAttrValue(item)">
                <el-option v-for="(it, index) in item.spuSaleAttrValueList" :key="it.id" :label="it.saleAttrValueName"
                  :value="it.id" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-form-item>
        <el-form-item label="图片名称">
          <el-table :data="skuForm.spuImageList" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="75">
            </el-table-column>
            <el-table-column label="图片" width="auto">
              <template #default="{ $index, row }">
                <img style="width: 100px;height: 100px;" :src="row.imgUrl" alt="">
              </template>
            </el-table-column>
            <el-table-column prop="imgName" label="名称" width="auto"> </el-table-column>
            <el-table-column label="操作">
              <template #default="{ $index, row }">
                <el-button v-if="!row.isDefault" type="success" @click="handleDefault($index, row)">
                  设置默认
                </el-button>
                <el-button v-else type="warning" disabled>
                  默认值
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item style="margin-left: 100px;">
          <el-button type="primary" @click="handleSaveSku">保存</el-button>
          <el-button @click="status = 0">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>

  <el-dialog v-model="dialogTableVisible" title="SKU列表" width="800">
    <el-table :data="gridData" border>
      <el-table-column property="skuName" label="sku名称" width="150" />
      <el-table-column property="price" label="sku价格" width="200" />
      <el-table-column property="weight" label="sku重量" />
      <el-table-column label="sku图片">
        <template #default="{ row }">
          <img :src="row.skuDefaultImg" style="width: 100px;height: 100px;" alt="">
        </template>
      </el-table-column>

    </el-table>
  </el-dialog>

</template>

<style scoped lang="scss">
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.btn {
  margin-bottom: 20px;
}

.page {
  margin-top: 20px;
  width: 100%;
}
</style>